package com.hupu.jrs.data.remote

import com.hupu.jrs.api.forum.ForumApi
import com.hupu.jrs.bean.ForumsData
import com.hupu.jrs.bean.MyForumsData
import com.hupu.jrs.data.ForumDataSource
import java.util.ArrayList
import javax.inject.Inject
import rx.Observable
import rx.functions.Func1

/**
 * Created by sll on 2016/6/3.
 */
class ForumRemoteDataSource @Inject
constructor(private val mForumApi: ForumApi) : ForumDataSource {

    override fun getForumList(forumId: String): Observable<List<Forum>> {
        return if (forumId == "0") {
            mForumApi.myForums.map(Func1<MyForumsData, List<Forum>> { myForumsData ->
                if (myForumsData != null && myForumsData.data != null) {
                    val data = myForumsData.data
                    for (forum in data!!.sub!!) {
                        forum.forumId = data.fid
                        forum.categoryName = data.name
                        forum.weight = 1
                    }
                    return@Func1 data.sub
                }
                null
            }).onErrorReturn { null }
        } else {
            mForumApi.forums.map(Func1<ForumsData, List<Forum>> { forumsData ->
                if (forumsData != null) {
                    val forumList = ArrayList<Forum>()
                    for (data in forumsData.data!!) {
                        if (data.fid == forumId) {
                            for (forums in data.sub!!) {
                                for (forum in forums.data!!) {
                                    forum.forumId = data.fid
                                    forum.categoryName = forums.name
                                    forum.weight = forums.weight
                                    forumList.add(forum)
                                }
                            }
                        }
                    }
                    return@Func1 forumList
                }
                null
            }).onErrorReturn { null }
        }
    }

    override fun removeForum(fid: String): Observable<Boolean>? {
        return null
    }
}
